package de.hska.util;

import static de.hska.util.LogUtil.begin;
import static de.hska.util.LogUtil.end;

import java.util.Locale;
import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class SpracheUiBean {
	private static final Log LOG = LogFactory.getLog(SpracheUiBean.class);
	private static final boolean DEBUG = LOG.isDebugEnabled();
	private Locale locale;
	
	public Locale getLocale() {
		return locale;
	}
	

	/**
	 */
	@Override
	public String toString() {
		return "{locale=" + locale + "}";
	}
	
	/**
	 */
	public String englisch() {
		if (DEBUG) begin(LOG, this);
		
		locale = Locale.ENGLISH;
		set();
		
		if (DEBUG) end(LOG, this);
		return null;
	}
	
	/**
	 */
	public String deutsch() {
		if (DEBUG) begin(LOG, this);
		
		locale = Locale.GERMAN;
		set();
		
		if (DEBUG) end(LOG, this);
		return null;
	}
	
	/**
	 */
	private String set() {
		if (DEBUG) begin(LOG, this);
		
		final FacesContext ctx = FacesContext.getCurrentInstance();
		ctx.getViewRoot().setLocale(locale);
		ctx.renderResponse();
		
		if (DEBUG) end(LOG, this);
		return null;
	}
	

	/**
	 * F&uuml;r den Aufruf bei "f:view locale=#{sprache.aktuell}"
	 */
	public Locale getAktuell() {
		if (DEBUG) begin(LOG, this);
		
		if (locale != null)
			return locale;
		
		final FacesContext ctx = FacesContext.getCurrentInstance();
		final Locale requestLocale = ctx.getExternalContext().getRequestLocale();

		if (DEBUG) end(LOG);
		return requestLocale;
	}
}
